var baseData = [];//存储预览的数据
var baseDataDownLoad = '';//导出数据格式
var dataJson = '';// 渲染时间轴的数据
var currentOld = '0';//
var currentNow = '0';//当前轮播位置
//new 筛选存储
var checkedBool = false;
var checkedTagArr = [];//筛选标签数组
var baseDataDownLoadNew = '';//导出数据格式
var dataJsonNew = '';// 渲染时间轴的数据
var baseDataNew = [];//
var SelectBoxNum = 0;//第几个被选中修改的盒子 annote：第一个 0
function getEventTimeList(page, size) {
  var def = $.Deferred();
  $.ajax({
    type: 'get',
    url: PUBLIC_PM.prefixUrl + '/eventTime-api/',
    data: {
      "page": page,
      "size": size
    },
    dataType: "json",
    success: function (data) {
      def.resolve(data.content);
      def.promise(data.content);
    },
    error: function (data) {
      def.reject(data);
      def.promise(data);
    }
  });
  return def;
}
//导入
$('#importBtn').on('click', function () {
  $('#importInput').click();
});
$('#importInput').change(function () {
  var file = this.files[0];
  var fileReader = new FileReader();
  fileReader.readAsText(file)
  fileReader.onload = function () {
    // $timeline = JSON.parse(fileReader.result);
    var data = fileReader.result;
    data = filterAjaxJsonToHtml(data)
    console.log(data);
    // baseData = JSON.parse(data);
    baseDataDownLoad = data;
    baseData = bibtexParse.toJSON(data);
    baseData = arrSortByProperty(baseData,'entryTags',true,true);
    setTimeout(() => {
      dataProcessing(baseData);
    }, 50);
    
  }
});
// getEventTimeList(0, 45).then(function (data) {
//   baseData = data.content;
//   dataProcessing(data.content);
// });
// 数据处理
function dataProcessing(data) {
  dataJson = {
    "timeline": {
      // "headline": {},
      "headline": '',
      "type": "default",
      "text": "",
      "startDate": "",
      "date": [],
      "era": []
    }
  };
  $.each(data, function (k, v) {
    // if (v.eventTime && v.subjectModifierContent) {
    v = v.entryTags;
    // if (v.year && v.abstract) {
      if (v.year) {
      var obj = {};
      // obj.startDate = v.eventTime.split("-").join(",");
      // obj.headline = v.subjectModifierContent.substr(0, 200);
      if (v.year.indexOf('-') > -1) {
        obj.startDate = v.year.split("-").join(",");
      } else {
        obj.startDate = v.year + ',01,01';
      }
      // obj.headline = v.abstract.substr(0, 200);
      obj.headline = v.title;
      var str = {
        "title": v.title,
        // "note": v.keywords,
        // "tag": v.mendeley_tags
        "tag": v.keywords
      };
      obj.headlineArr = str;
      var text = `<div class="box timeLineData"></div>`;
      var textLine = ''
      for (i in v) {
        if (i.indexOf("Id") !== -1 || i === "subjectModifierType" || i === "eventTime") {
          continue;
        }
        // text += `<div class="box-li" id="box_li_${k}_${i}"><div class="left"><p>${i}: </p></div><div class="right"><p>${v[i]}</p></div></div>`;
        if (i === 'annote') {
          //可编辑
          textLine = `<div class="box-li" param-id="box_li_${k}_${i}"><div class="left"><p>${i}: </p></div><div class="right"><textarea id="box_li_${k}_${i}">${v[i]}</textarea></div></div>` + textLine;
        } else {
          textLine += `<div class="box-li" param-id="box_li_${k}_${i}"><div class="left"><p>${i}: </p></div><div class="right"><div id="box_li_${k}_${i}">${v[i]}</div></div></div>`;
        }
      }
      text = textLine + `</div>`;
      obj.text = text;
      console.log(obj)
      dataJson.timeline.date.push(obj);
    }
  });
  // console.log('dataJson',dataJson)
  // $('#timeline').empty();
  // createStoryJS({
  //   type: 'timeline',
  //   width: '100%',
  //   height: '600',
  //   source: dataJson,
  //   embed_id: 'timeline',
  //   debug: true
  // });
  checkedBool = false;
  timelineCreate(dataJson);
};
//创建时间轴
function timelineCreate(json) {
  $('#timeline').empty();
  createStoryJS({
    type: 'timeline',
    width: '100%',
    height: $('.timeline-box').height() - 53 - 10 * 2,
    source: json,
    embed_id: 'timeline',
    debug: true
  });
}
//当前页时间轴，加载完成事件
function svgCreate($current_slide) {
  currentNow = Number($current_slide);
  // console.log('currentNow', currentNow);
  textareafn();//添加监听事件
};
//下载json文件
$('#exportJson').on('click', function () {
  if (checkedBool) {
    // 筛选
    if(baseDataNew.length > 0){
        downDataFixNew(baseDataNew);//导出数据处理
    } else {
      alert('导出数据为空')
    }
  } else {
    if(baseData.length > 0){
      downDataFix(baseData);//导出数据处理
    } else {
      alert('导出数据为空')
    }
  }
});
function saveHandler(dataDown) {
  // var content = JSON.stringify(baseData);
  // var blob = new Blob([content], {type: "text/plain;charset=utf-8"});
  // saveAs(blob, "save.json");
  // dataDown = filterAjaxJsonToHtml(dataDown);
  var content = dataDown.replace(/^\"|\"$/g, '');
  var blob = new Blob([content], {type: "text/plain;charset=utf-8"});
  saveAs(blob, "save.bib");
};
function filterAjaxJsonToHtml(str) {
  str = str.replace(new RegExp("\r\n", "gm"), "");//处理回车换行
  return str;
};
//导出数据处理
function downDataFix(baseData) {
  baseDataDownLoad = '';
  $.each(baseData, function (index, val) {
    val = val.entryTags;
    var str = '@article{Grubaugh2020,' + '\r\n';
    for (i in val) {
      str += i + '={' + val[i] + '},' + '\r\n';
    }
    str += '}';
    // return str;
    baseDataDownLoad += str;
  });
  saveHandler(baseDataDownLoad);//下载数据
};
//导出数据处理-new 筛选
function downDataFixNew(baseDataNew) {
  baseDataDownLoadNew = '';
  $.each(baseDataNew, function (index, val) {
    val = val.entryTags;
    var str = '@article{Grubaugh2020,' + '\r\n';
    for (i in val) {
      str += i + '={' + val[i] + '},' + '\r\n';
    }
    str += '}';
    // return str;
    baseDataDownLoadNew += str;
  });
  saveHandler(baseDataDownLoadNew);//下载数据
};
//自适应高度，无滚动条
function makeExpandingArea(el) {
  var timer = null;
  //由于ie8有溢出堆栈问题，故调整了这里
  var setStyle = function (el, auto) {
    if (auto) el.style.height = 'auto';
    el.style.height = el.scrollHeight + 'px';
  };
  var delayedResize = function (el) {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
    timer = setTimeout(function () {
      setStyle(el)
    }, 200);
  };
  if (el.addEventListener) {
    el.addEventListener('input', function () {
      setStyle(el, 1);
    }, false);
    setStyle(el);
  } else if (el.attachEvent) {
    el.attachEvent('onpropertychange', function () {
      setStyle(el)
    });
    setStyle(el)
  }
  if (window.VBArray && window.addEventListener) { //IE9
    el.attachEvent("onkeydown", function () {
      var key = window.event.keyCode;
      if (key == 8 || key == 46) delayedResize(el);
    });
    el.attachEvent("oncut", function () {
      delayedResize(el);
    }); //处理粘贴
  }
};

//添加监听事件
function textareafn() {
  var boxArr = $('.slider-item-container .slider-item').eq(currentNow).find('.container .box-li');
  if (!boxArr.eq(SelectBoxNum).hasClass('active')) {
    boxArr.eq(SelectBoxNum).addClass('active');
    var param_id = boxArr.eq(SelectBoxNum).attr('param-id');
    var textarea = $("#" + param_id + "")[SelectBoxNum];
    makeExpandingArea(textarea);
    // $.each(boxArr, function (index, value) {
    //   var param_id = boxArr.eq(index).attr('param-id');
    //   var textarea = $("#" + param_id + "")[0];
    //   makeExpandingArea(textarea);
    // })
    $(document).on('change', "#" + param_id + "", function () {
      $("#" + param_id + "").html($("#" + param_id + "").val());
      console.log($("#" + param_id + "").val());
      if (checkedBool) {
        // 修改数据-筛选状态
        baseDataNew[currentNow].entryTags.annote = $("#" + param_id + "").val();
      } else {
        baseData[currentNow].entryTags.annote = $("#" + param_id + "").val();
      }
    });
  }
};
//右侧选择框部分
var dataListJson = '';// 复选框导入列表数据
//导入-点击
$('#importCheckedBtn').on('click', function () {
  $('#importCheckedInput').click();
});
//选择确定-点击
$('#checkedOK').on('click', function () {
  checkedTagArr = [];//被选中的标签
  var lis = $('#dataListLi li');
  for (var li_i = 0; li_i < lis.length; li_i++) {
    var thisli = $('#dataListLi li').eq(li_i).find('input');
    var bool = $('#dataListLi li').eq(li_i).find('input').prop('checked');
    if (bool) {
      checkedTagArr.push(thisli.val());
    }
  }
  checkedValFix(baseData);//处理筛选标签
  console.log(checkedTagArr);
});
//处理筛选标签
function checkedValFix(baseData) {
  // var checkedDataJson = arr.timeline.date;
  if (checkedTagArr.length > 0) {
    baseDataNew = [];
    $.each(baseData, function (index, val) {
      var tagArr = val.entryTags.keywords.split(',');
      // var tagArr = val.headlineArr.tag.split(',');
      var bool = IsArrDiff(tagArr, checkedTagArr);
      if (bool) {
        // arr1,在arr2中
        baseDataNew.push(val);
      }
    });
    if (baseDataNew.length > 0) {
      console.log(baseDataNew);
      dataProcessingNew(baseDataNew);
    } else {
      alert('未查询到数据！')
    }
  } else {
    alert('筛选条件不能为空！')
  }
};
// 数据处理-new checked
function dataProcessingNew(datanew) {
  // dataJsonNew = {};
  dataJsonNew = {
    "timeline": {
      // "headline": {},
      "headline": '',
      "type": "default",
      "text": "",
      "startDate": "",
      "date": [],
      "era": []
    }
  };
  $.each(datanew, function (k, v) {
    // if (v.eventTime && v.subjectModifierContent) {
    v = v.entryTags;
    // if (v.year && v.abstract) {
      if (v.year) {
      var obj = {};
      // obj.startDate = v.eventTime.split("-").join(",");
      // obj.headline = v.subjectModifierContent.substr(0, 200);
      if (v.year.indexOf('-') > -1) {
        obj.startDate = v.year.split("-").join(",");
      } else {
        obj.startDate = v.year + ',01,01';
      }
      // obj.headline = v.abstract.substr(0, 200);
      obj.headline = v.title;
      var str = {
        "title": v.title,
        // "note": v.keywords,
        // "tag": v.mendeley_tags
        "tag": v.keywords
      };
      obj.headlineArr = str;
      var text = `<div class="box timeLineData">`;
      var textLine = '';
      for (i in v) {
        if (i.indexOf("Id") !== -1 || i === "subjectModifierType" || i === "eventTime") {
          continue;
        }
        // text += `<div class="box-li" id="box_li_${k}_${i}"><div class="left"><p>${i}: </p></div><div class="right"><p>${v[i]}</p></div></div>`;
        if (i === 'annote') {
          //可编辑
          textLine = `<div class="box-li" param-id="box_li_${k}_${i}"><div class="left"><p>${i}: </p></div><div class="right"><textarea id="box_li_${k}_${i}">${v[i]}</textarea></div></div>` + textLine;
        } else {
          textLine += `<div class="box-li" param-id="box_li_${k}_${i}"><div class="left"><p>${i}: </p></div><div class="right"><div id="box_li_${k}_${i}">${v[i]}</div></div></div>`;
        }
      }
      text = textLine + `</div>`;
      obj.text = text;
      dataJsonNew.timeline.date.push(obj);
    }
  });
  checkedBool = true;
  timelineCreate(dataJsonNew);
};
//JSON 对象实现深拷贝
function jsonDeepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
};
//判断两个数组是否相同
function IsArrDiff(arr1, arr2) {
  // arr1,是否在arr2中
  var flag = true;
  // if (arr1.length > arr2.length) {
  //   flag = false;
  // } else {
    arr1.some(function (item) {
      if (arr2.indexOf(item) === -1) {
        flag = false;
      }else{
        flag = true;
        return true;
      }
    })
  // }
  return flag;
};
//导入
$('#importCheckedInput').change(function () {
  var objFile = document.getElementById("importCheckedInput");
  if (objFile.value == "") {
    alert("txt不能空")
    return false;
  }
  var files = $('#importCheckedInput').prop('files'); //获取到文件列表
  console.log(files.length);
  if (files.length == 0 || files.length > 1) {
    alert('请选择一个文件');
    return false;
  } else {
    for (var i = 0; f = files[i]; i++) {
      var reader = new FileReader(); //新建一个FileReader
      reader.readAsText(files[i], "GB2312"); //读取文件
      reader.onload = function (evt) { //读取完文件之后会回来这里
        dataListJson = evt.target.result; // 读取文件内容
        dataListJson = dataListJson.split('\r\n');//按回车 划分对象
        console.log(dataListJson);
        dataLiatHtml(dataListJson);
      }
    }
  }
});
//右侧复选框，添加html
function dataLiatHtml(data) {
  var str = '';
  for (var i = 0; i < data.length; i++) {
    str += '<li><label><input type="checkbox" name="title" checked="checked" value="' + data[i] + '">' + data[i] + '</label></li>'
  }
  $('#dataListLi').empty().append(str);
};
// 1.排序
function arrSortByProperty(arr, property, upAndDown, dateBoolean) {
  /**
   * 数组对象排序，根据对象属性
   *  eg：
   *   var arr = [
   {name:'zopp',age:0},
   {name:'gpp',age:18},
   {name:'yjj',age:8}
   ];
   param:
   arr:[{},{}]数组对象
   property:age,根据对象属性排序
   upAndDown:true,升序
   dateBoolean:true,字段是否是日期'2020-01-01'
   arrSortByProperty(arr,'age',true,true);
   */
  var newArr = arr.sort(compare(property, upAndDown, dateBoolean));
  function compare(property, upAndDown) {
    return function (a, b) {
      if (dateBoolean) {//日期格式
        if (upAndDown) {//升序
          return Date.parse(a[property].year) - Date.parse(b[property].year);
        } else {//降序
          return Date.parse(b[property]) - Date.parse(a[property]);
        }
      } else {//非日期格式
        if (upAndDown) {//升序
          return a[property] - b[property];
        } else {//降序
          return b[property] - a[property];
        }
      }
    }
  }
  // console.log('newArr',newArr)
  return newArr
};